<template>
  <div class="login-wrap">
    <div class="nav-back">
      <span class="back-icon">←</span>
    </div>

    <div class="title-block">
      <h1 class="brand-line">欢迎使用</h1>
      <h1 class="brand-name">安途代驾</h1>
    </div>

    <el-form class="login-form" @submit.prevent>
      <el-form-item>
        <el-input
          v-model="phone"
          placeholder="输入手机号"
          maxlength="11"
          clearable
        />
      </el-form-item>

      <el-form-item>
        <el-input
          v-model="password"
          :type="passwordVisible ? 'text' : 'password'"
          placeholder="输入密码"
          clearable
        >
          <template #suffix>
            <el-icon class="clickable" @click="passwordVisible = !passwordVisible">
              <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
                <path fill="currentColor" d="M12 5C7 5 2.73 8.11 1 12c1.73 3.89 6 7 11 7s9.27-3.11 11-7c-1.73-3.89-6-7-11-7Zm0 12a5 5 0 1 1 0-10 5 5 0 0 1 0 10Zm0-8a3 3 0 1 0 .001 6.001A3 3 0 0 0 12 9Z"/>
              </svg>
            </el-icon>
          </template>
        </el-input>
      </el-form-item>

      <div class="helper-row">
        <a class="helper-link">忘记密码</a>
      </div>

      <el-button 
        class="primary-btn" 
        type="primary" 
        :disabled="loginDisabled"
        :loading="loginLoading"
        @click="handleLogin"
      >
        登录
      </el-button>
    </el-form>

    <div class="divider">- 第三方账号登录 -</div>

    <div class="third-row">
      <el-button class="ding-btn" :loading="loading" :disabled="loading" @click="handleDingtalkLogin">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200" class="ding-icon">
            <path fill="#1E88E5" d="M100 0C44.77 0 0 44.77 0 100s44.77 100 100 100 100-44.77 100-100S155.23 0 100 0z"/>
            <path fill="#FFF" d="M146.66 76.66c-2.67-1.33-14.67-7.33-15.33-8-.67-.67-1.33-2-1.33-2s8.67-8 10.67-11.33c2-3.33.66-6.67-1.34-8-2-1.33-5.33-1.33-7.33 1.34-2 2.66-8.67 11.33-8.67 11.33s-6.66-3.33-8-4c-1.33-.67-3.33-1.33-5.33.67-2 2-1.33 4.66.67 6.66 2 2 12 6.67 12 6.67s-9.34 8-12 10.66c-2.67 2.67-1.34 6 1.33 8 2.67 2 6 .67 8-1.33 2-2 8.67-8.67 8.67-8.67s6.66 3.33 8 4c1.33.67 3.33 1.33 5.33-.67 2-2 1.33-4.66-.67-6.66z"/>
          </svg>
          {{ loading ? '正在跳转钉钉...' : '钉钉登录' }}
        </el-button>
      </div>

    <div class="footer-row">
      <span>没有账户？</span>
      <a class="primary-link" @click="goToRegister">注册</a>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'
import axios from 'axios'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const loginLoading = ref(false)
const phone = ref('')
const password = ref('')
const passwordVisible = ref(false)

const loginDisabled = computed(() => !(phone.value && password.value))

const goToRegister = () => {
  router.push('/register')
}

const handleLogin = async () => {
  // 验证表单
  if (!phone.value || !password.value) {
    ElMessage.warning('请输入账号和密码')
    return
  }

  try {
    loginLoading.value = true
    
    const response = await axios.post('http://127.0.0.1:8888/users/login', {
      account: phone.value,
      password: password.value
    })

    if (response.data.code === 200) {
      // 登录成功
      const { token, userid } = response.data.data
      userStore.setToken(token)
      localStorage.setItem('user_id', userid)
      ElMessage.success('登录成功')
      router.push('/')
    } else {
      ElMessage.error(response.data.message || '登录失败')
    }
  } catch (error) {
    // 处理错误响应
    if (error.response && error.response.data) {
      const errorDetail = error.response.data.detail
      if (typeof errorDetail === 'object' && errorDetail.message) {
        ElMessage.error(errorDetail.message)
      } else if (typeof errorDetail === 'string') {
        ElMessage.error(errorDetail)
      } else {
        ElMessage.error('登录失败，请稍后重试')
      }
    } else {
      ElMessage.error('网络错误，请检查连接')
    }
    console.error('登录失败:', error)
  } finally {
    loginLoading.value = false
  }
}

const handleDingtalkLogin = async () => {
  try {
    loading.value = true
    window.location.href = 'http://127.0.0.1:8888/dingtalk/login'
  } catch (error) {
    loading.value = false
    ElMessage.error('钉钉登录跳转失败，请稍后重试')
    console.error('钉钉登录失败:', error)
  }
}

onMounted(() => {
  const url = new URL(window.location.href)
  const token = url.searchParams.get('token')
  const user_id = url.searchParams.get('user_id')
  console.log(user_id, 66666);
  
  if (token) {
    userStore.setToken(token)
    localStorage.setItem('user_id', user_id)
    url.searchParams.delete('token')
    window.history.replaceState({}, document.title, url.toString())
    router.push('/')
    ElMessage.success('登录成功')
  }
})
</script>

<style scoped>
.login-wrap {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 16px 20px 28px;
  background: #fff;
}
.nav-back { height: 28px; display: flex; align-items: center; }
.back-icon { font-size: 18px; color: #2c2c2c; }

.title-block { margin: 8px 0 18px; }
.brand-line { margin: 0; font-size: 26px; color: #111; }
.brand-name { margin: 6px 0 0; font-size: 26px; color: #111; font-weight: 700; }

.login-form { margin-top: 8px; }
.login-form :deep(.el-input__wrapper) { padding: 10px 12px; }

.helper-row { text-align: right; margin: 4px 0 10px; }
.helper-link { color: #606266; font-size: 13px; cursor: pointer; }

.primary-btn { width: 100%; height: 44px; font-size: 16px; }

.divider { text-align: center; color: #909399; margin: 22px 0 10px; font-size: 13px; }

.third-row { display: flex; justify-content: center; margin-bottom: 24px; }
.ding-btn { display: inline-flex; align-items: center; gap: 8px; }
.ding-icon { width: 20px; height: 20px; }

.footer-row { text-align: center; color: #909399; }
.primary-link { color: #409EFF; margin-left: 6px; cursor: pointer; }

.clickable { cursor: pointer; }
</style>
